/***********************************************************************t*
	> File Name: client.cpp
	> Author: Wu Junqiang
	> Mail: 15769154659@163.com 
	> Created Time: 2018年01月31日 星期三 17时06分33秒
	> Note: 测试客户端 
 ************************************************************************/

#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <assert.h>
#include <string.h>
#include <unistd.h>

#include <iostream>

#include "Util.h"
#define SOCK_PORT 10000
#define BUFFER_LENGTH 1024
using namespace std;

int main()
{
	FILE* stream;
	int sockfd;
	int tempfd;
	struct sockaddr_in s_addr_in;
	char data_send[BUFFER_LENGTH];
    char data_recv[BUFFER_LENGTH];
	memset(data_send,0,BUFFER_LENGTH);
	memset(data_recv,0,BUFFER_LENGTH);

	sockfd= socket(AF_INET,SOCK_STREAM,0);
	if(sockfd == -1)
	{
		fprintf(stderr,"socket error!\n");
		exit(1);
	}

	memset(&s_addr_in,0,sizeof(s_addr_in));
	s_addr_in.sin_addr.s_addr = inet_addr("127.0.0.1");
	s_addr_in.sin_family= AF_INET;
	s_addr_in.sin_port = htons(SOCK_PORT);

	tempfd = connect(sockfd,(struct sockaddr*)(&s_addr_in),sizeof(s_addr_in));
	if(tempfd == -1)
	{
		fprintf(stderr,"Connect error!\n");
		exit(1);
	}

	while(true)
	{
        Msg data;
		printf("Please input something you want to (intput \"quit\" to quit):\n");
//		fgets(data_send,BUFFER_LENGTH,stream);
		const char* str = "{\"protocol\":\"login\",\"msg\":[{\"name\":\"jiao\"}]}";
		tempfd = send(sockfd, str,BUFFER_LENGTH,0);
		scanf("%s\n",data_send);
		if(tempfd == -1)
		{
			fprintf(stderr,"write error\n");
			exit(0);
		}
		if(strcmp(data_send,"quit")== 0)
		{
			break;
		}
		else
		{
        

			tempfd = recv(sockfd,data_recv,sizeof(Msg),0);
            
			assert(tempfd != -1);
			printf("%s\n",data_recv);
            memcpy(&data,data_recv,BUFFER_LENGTH);

    //        cout << "data_recv Length:" << sizeof(data_recv1) << endl;
            cout << "length:" << data.len << endl;
            printf("%s\n",data.protocol);
            cout << "ch_msg: " << data.ch_msg<< endl;
          // print("%s\n",data.ch_msg);
//            printf("%s\n",&data_recv.ch_msg) ;
//vmlinuz.a_stomic_flag_test_and_set_explicitrintf("%0x\n", data_recv);
			memset(data_send,0,BUFFER_LENGTH);
//			memset(data_recv,0,BUFFER_LENGTH);
		}
	}
    int ret = shutdown(sockfd,SHUT_WR);
	assert(ret != -1);
	return 0;
}
